using System;

namespace codebase.UI
{
    public class CheckBox : Control
    {
        public delegate void CheckStateChangedDelegate(Boolean check);

        public event CheckStateChangedDelegate CheckStateChanged;

        internal void DoCheckStateChanged(Boolean check)
        {
            if (CheckStateChanged != null) CheckStateChanged(check);
        }

        Boolean _IsChecked;

        public Boolean IsChecked
        {
            get { return _IsChecked; }
            set
            {
                _IsChecked = value;
                DoCheckStateChanged(IsChecked);
            }
        }

        public int ForeColor;
        public int CheckColor;
        public String Text;

        public CheckBox(int x, int y, String txt, int tc, int bgc, int cc, Window parent)
        {
            Init(x, y, txt, tc, bgc, cc,parent);
        }

        void Init(int x, int y, String txt, int tc, int bgc, int cc, Window parent)
        {
            Parent = parent;

            Left = x * Parent.Parent.screen.CharacterWidth;
            Top = y * Parent.Parent.screen.CharacterHeight;

            Text = txt;
            Height = Parent.Parent.screen.CharacterHeight;
            BackgroundColor = bgc;
            ForeColor = tc;
            CheckColor = cc;

            updateWidth();
        }

        void updateWidth()
        {
            Width = (Text.Length + 1) * Parent.Parent.screen.CharacterWidth;
        }

#if !PC
        public override void touchDown(object o, TouchEventArgs e)
        {
            updateWidth();

            if (IsPointInControl(e.x, e.y))
            {
                _IsChecked = !_IsChecked;
                DoCheckStateChanged(_IsChecked);
                Draw();
            }
        }
#endif

        protected override void DrawAll()
        {
            Parent.Parent.screen.DrawText(Text, Left + Parent.Left + Parent.Parent.screen.CharacterWidth, Top + Parent.Top, false, BackgroundColor, ForeColor);
            Draw();
        }

        protected override void Draw()
        {
            Parent.Parent.screen.DrawFilledRectangle(Left + Parent.Left, Top + Parent.Top, Left + Parent.Left + Parent.Parent.screen.CharacterWidth - 1, Top + Parent.Top + Parent.Parent.screen.CharacterHeight - 1, (int)BackgroundColor);
            Parent.Parent.screen.DrawFilledRectangle(Left + Parent.Left, Top + Parent.Top, Left + Parent.Left + Parent.Parent.screen.CharacterWidth - 1, Top + Parent.Top + Parent.Parent.screen.CharacterHeight - 2, IsChecked ? (int)CheckColor : (int)BackgroundColor);
            Parent.Parent.screen.DrawRectangle(Left + Parent.Left, Top + Parent.Top, Left + Parent.Left + Parent.Parent.screen.CharacterWidth - 1, Top + Parent.Top + Parent.Parent.screen.CharacterHeight - 2, ForeColor);
        }
    }
}
